package server;

import pojo.Wrapper;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

/**
 * @author chenx
 * @date 2021/8/26-22:57
 */
public class RequestProcessor extends Thread {

    private Socket socket;
    private List<Wrapper> list;

    public RequestProcessor(Socket socket, List<Wrapper> list) {
        this.socket = socket;
        this.list = list;
    }

   /* private Map<String,HttpServlet> servletMap;

    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap) {
        this.socket = socket;
        this.servletMap = servletMap;
    } }*/

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            ///demo1/index.html
            String[] split = request.getUrl().split("/");
            String context = split[1];
            System.out.println("context = " + context);
            HttpServlet httpServlet = null;
            for (Wrapper wrapper : list) {
                if (wrapper.getContext().equals(context)) {
                    httpServlet = wrapper.getServlet();
                    break;
                }
            }
            if (httpServlet == null) {
                response.outputHtml(request.getUrl());
            } else {
                // 动态资源servlet请求
                httpServlet.service(request, response);
            }
            // 静态资源处理
            /*if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }*/

            socket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}